package com.zstu.lvxiang.controller;


import com.zstu.lvxiang.config.AccessLimit;
import com.zstu.lvxiang.pojo.Student;
import com.zstu.lvxiang.service.IStudentService;
import com.zstu.lvxiang.utils.MD5Utils;
import com.zstu.lvxiang.vo.LoginVo;
import com.zstu.lvxiang.vo.RespBean;
import com.zstu.lvxiang.vo.RespBeanEnum;
import com.zstu.lvxiang.vo.StudentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Trafalgar
 * @since 2022-03-16
 */
@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    IStudentService studentService;

    /**
     * 注册
     * @param studentVo
     * @return
     */
    @PutMapping("/register")
    public RespBean register(@Valid StudentVo studentVo) {
        if (studentService.getById(studentVo.getSno()) != null) {
            return RespBean.error(RespBeanEnum.REGISTER_ERROR);
        }
        String pwd = MD5Utils.inputPassToFromPass(studentVo.getPassword());
        String grade = studentVo.getSno().substring(0, 4) + "级";
        boolean flag = studentService.save(new Student(studentVo.getSno(), studentVo.getName(), pwd,
                studentVo.getClassroom(), grade, studentVo.getSex(), 0, null, false));
        if (flag) {
            return RespBean.success();
        }
        return RespBean.error(RespBeanEnum.ERROR);
    }

    /**
     * 登录
     * @param loginVo
     * @param response
     * @return
     */
    @PostMapping("/login")
    public RespBean login(@Valid LoginVo loginVo, HttpServletResponse response) {
        return studentService.doLogin(loginVo, response);
    }

    /**
     * 打卡
     * @param sno
     * @return
     */
    @AccessLimit
    @GetMapping("/punch")
    public RespBean punch(@RequestAttribute("sno") String sno) {
        return studentService.punch(sno);
    }

    /**
     * 登出
     * @param sno
     * @param response
     * @return
     */
    @AccessLimit
    @GetMapping("/logout")
    public RespBean logout(@RequestAttribute("sno") String sno,
                           HttpServletResponse response) {
        Cookie cookie = new Cookie("sno", "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return RespBean.success();
    }
}
